package com.match.competition_sub.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.match.competition_sub.entity.Teacher;
import com.match.competition_sub.excel.TeacherData;
import com.match.competition_sub.service.TeacherService;
import com.match.servicebase.exceptionhandler.AdiosException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class TeacherExcelListener extends AnalysisEventListener<TeacherData> {
    public TeacherService teacherService;
    public TeacherExcelListener() {}
    public TeacherExcelListener(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    //读取excel内容，一行一行进行读取
    @Override
    public void invoke(TeacherData teacherData, AnalysisContext analysisContext) {
        if (teacherData == null) {
              throw new AdiosException(20001, "文件数据为空");
              }
        //判断是否有相同的职工号，没有进行添加
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        Teacher teacher=existTeaNumber(teacherService,teacherData.getNumber());
        if (teacher==null){
            //没有相同的职工号进行添加
            teacher=new Teacher();
            teacher.setNumber(teacherData.getNumber());
            teacher.setName(teacherData.getName());
            teacher.setPassword(passwordEncoder.encode(teacherData.getPassword()));
            teacher.setSex(teacherData.getSex());
            teacher.setDepartment(teacherData.getDepartment());
            teacher.setRole(teacherData.getRole());
            teacher.setJobTitle(teacherData.getJobTitle());
            teacher.setPhone(teacherData.getPhone());
            teacher.setAvatar("https://adios.oss-cn-beijing.aliyuncs.com/2021/11/22/d9b55038c3f44a05ad9bdbfc650a34a4file.png");
            teacherService.save(teacher);
        }
    }

    //判断职工号是否存在的方法
    private Teacher existTeaNumber(TeacherService teacherService, String number) {
        QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
        teacherQueryWrapper.eq("number",number);
        Teacher one = teacherService.getOne(teacherQueryWrapper);
        return one;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }
}
